const db = require('../db/mysqlconfig')
const cb = require('../promise/cb')
exports.getMangerList = async(req, res) => {
    // res.ResInfo('ok')
    var key = req.query.query
    var pagenum = parseInt(req.query.pagenum)
    var pagesize = parseInt(req.query.pagesize)
    var total = 0
    var managers = ''
    sql = "select count(*) as from  count sp_manager"

    //用户有查询行为
    if (key) {
        sql += " where mg_name like ?"
        console.log(sql)
        managers = await cb(sql, ["%" + key + "%"]).catch(function(err) {
            res.ResInfo(err)
        })
        total = managers[0]["count"]
    } else { //用户没有查询行为
        managers = await cb(sql).catch(function(err) {
            res.ResInfo(err)
        })
        total = managers[0]["count"]
    }


    var offset = (pagenum - 1) * pagesize
    if (offset > total) //如果偏移量比总数大，那么偏移量等于总数
        offset = total
    limit = pagesize

    sql = "select * from sp_manager as mgr left join sp_role as role on mgr.role_id=role.role_id"


    //用户有查询行为
    if (key) {
        sql += " where mg_name like ? limit ?,? "
        managers = await cb(sql, ["%" + key + "%", offset, limit]).catch(function(err, result) {
            res.ResInfo(err)
        })
    } else { //用户没有查询行为
        managers = await cb(sql, [offset, limit]).catch(function(err) {
            res.ResInfo(err)
        })
    }
    retManagers = []
    for (idx in managers) {
        var manager = managers[idx]
        var role_name = manager.role_name
        if (!manager.role_id) { //如何role_id=0那么就是超级管理员
            role_name = "超级管理员"
        }
        retManagers.push({
            "id": manager.mg_id,
            "username": manager.mg_name,
            "role_name": role_name,
            "mobile": manager.mg_mobile,
            "mg_state": manager.mg_state,
            "email": manager.mg_email,
            "create_time": manager.mg_time,
        })
    }

    var resData = {}
    resData["total"] = total
    resData["pagenum"] = pagenum
    resData["users"] = retManagers
    res.ResInfo("获取列表成功", 200, resData)
}